package com.ruoyi.project.zxbd.controller;

import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.framework.web.domain.TreeSelect;
import com.ruoyi.project.zxcrm.domain.BdGoodsCategory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.common.zx.PageData;
import com.ruoyi.project.zxbd.mapper.BdGoodsCategoryMapper;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;

/**
 * 物料产品分类Controller
 *
 * @author zx
 * @date 2023-05-23
 */
@RestController
@RequestMapping("/zxbd/category")
public class BdGoodsCategoryController extends BaseController {

    @Autowired
    private BdGoodsCategoryMapper bdGoodsCategoryMapper;

    /**
     * 查询物料产品分类列表
     */
    @PreAuthorize("@ss.hasPermi('zxbd:category:list')")
    @GetMapping("/list")
    public AjaxResult list(BdGoodsCategory bdGoodsCategory) {
        List<BdGoodsCategory> list = bdGoodsCategoryMapper.selectBdGoodsCategoryList(bdGoodsCategory);
        return AjaxResult.success(list);
    }

    @PreAuthorize("@ss.hasPermi('zxbd:category:list')")
    @GetMapping("/TreeList")
    public AjaxResult TreeList(BdGoodsCategory bdGoodsCategory) {
        List<BdGoodsCategory> list = bdGoodsCategoryMapper.selectBdGoodsCategoryList(bdGoodsCategory);
        List<BdGoodsCategory> collect = list.stream().filter(a -> a.getParentId() == 0)
                .map(a -> {
                    a.setChildren(extract(a, list));
                    return a;
                }).collect(Collectors.toList());
        return AjaxResult.success(collect.stream().map(TreeSelect::new).collect(Collectors.toList()));
    }

    private List<BdGoodsCategory> extract(BdGoodsCategory pd, List<BdGoodsCategory> list) {
        List<BdGoodsCategory> collect = list.stream().filter(a -> a.getParentId().equals(pd.getId()))
                .map(a -> {
                    a.setChildren(extract(a, list));
                    return a;
                }).collect(Collectors.toList());
        return collect;
    }
    /**
     * 导物料产品分类列表
     */
    @PreAuthorize("@ss.hasPermi('zxbd:category:export')")
    @Log(title = "物料产品分类", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BdGoodsCategory bdGoodsCategory) {
        List<BdGoodsCategory> list = bdGoodsCategoryMapper.selectBdGoodsCategoryList(bdGoodsCategory);
        ExcelUtil<BdGoodsCategory> util = new ExcelUtil<>(BdGoodsCategory.class);
        util.exportExcel(response, list, "物料产品分类数据");
    }

    /**
     * 获取物料产品分类详细信息
     */
    @PreAuthorize("@ss.hasPermi('zxbd:category:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(bdGoodsCategoryMapper.selectBdGoodsCategoryById(id));
    }


    @GetMapping()
    public AjaxResult getInfoById(Long id) {
        List<BdGoodsCategory> bdGoodsCategories = bdGoodsCategoryMapper.selectBdGoodsCategoryList(null);
        return success(bdGoodsCategories);
    }

    /**
     * 新增物料产品分类
     */
    @PreAuthorize("@ss.hasPermi('zxbd:category:add')")
    @Log(title = "物料产品分类", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PageData pd) {
        Integer parent_id = (Integer) pd.get("parent_id");
        if (parent_id == null) pd.put("parent_id", 0);
        extracted(pd);
        return toAjax(bdGoodsCategoryMapper.insertBdGoodsCategory(pd));
    }

    private void extracted(@RequestBody PageData pd) {
        boolean flag = true;
        Integer parentId = (Integer) pd.get("parent_id");
        List<Integer> list = new ArrayList<>();
        list.add(parentId);
        while (flag) {
            PageData pageData = bdGoodsCategoryMapper.selectBdGoodsCategoryById(parentId.longValue());
            if (pageData == null) {
                pd.put("ancestors", parentId+"");
                return;
            }
            Long pid = (Long) pageData.get("parent_id");
            parentId = pid.intValue();
            list.add(parentId);
            String s = "";
            if (parentId == 0) {
                flag = false;
                Collections.reverse(list);
                for (int i = 0; i < list.size(); i++) {
                    if (i == 0) s = list.get(i) + "";
                    else s = s + "," + list.get(i);
                }
                pd.put("ancestors", s);
            }
        }
    }

    /**
     * 修改物料产品分类
     */
    @PreAuthorize("@ss.hasPermi('zxbd:category:edit')")
    @Log(title = "物料产品分类", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PageData pd) {
        Integer parent_id = (Integer) pd.get("parent_id");
        Integer pid = (Integer) pd.get("id");
        if (parent_id.equals(pid)) {
            return AjaxResult.error(90002, "不能修改到当前节点");
        }
        PageData pageData = bdGoodsCategoryMapper.selectBdGoodsCategoryById(parent_id.longValue());
        if (pageData != null) {
            String ancestors = (String) pageData.get("ancestors");
            Integer id = (Integer) pd.get("id");
            if (ancestors.contains(id + "")) {
                return AjaxResult.error(90001, "禁止修改到下级节点");
            }
        }
        extracted(pd);
        return toAjax(bdGoodsCategoryMapper.updateBdGoodsCategory(pd));
    }

    /**
     * 删除物料产品分类
     */
    @PreAuthorize("@ss.hasPermi('zxbd:category:remove')")
    @Log(title = "物料产品分类", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(bdGoodsCategoryMapper.deleteBdGoodsCategoryByIds(ids));
    }
}
